<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <u-icon name="search" size="20" color="#999"></u-icon>
        <input
          v-model="keyword"
          class="search-input"
          type="text"
          placeholder="搜索菏泽本地信息..."
          confirm-type="search"
          @confirm="handleSearch"
          @input="onInput"
        />
        <u-icon
          v-if="keyword"
          name="close-circle-fill"
          size="18"
          color="#ccc"
          @click="clearKeyword"
        ></u-icon>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>

    <!-- 搜索历史/热门搜索 -->
    <view v-if="!hasSearched" class="suggestion-section">
      <!-- 搜索历史 -->
      <view v-if="searchHistory.length > 0" class="history-section">
        <view class="section-header">
          <text class="section-title">搜索历史</text>
          <u-icon name="trash" size="18" color="#999" @click="clearHistory"></u-icon>
        </view>
        <view class="tag-list">
          <view
            v-for="(item, index) in searchHistory"
            :key="index"
            class="tag-item"
            @click="searchByKeyword(item)"
          >
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 热门搜索 -->
      <view class="hot-section">
        <view class="section-header">
          <text class="section-title">热门搜索</text>
        </view>
        <view class="tag-list">
          <view
            v-for="(item, index) in hotKeywords"
            :key="index"
            class="tag-item hot"
            @click="searchByKeyword(item)"
          >
            <u-icon name="fire" size="16" color="#fa3534"></u-icon>
            {{ item }}
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <scroll-view
      v-else
      class="result-section"
      scroll-y
      @scrolltolower="onLoadMore"
    >
      <view class="result-header">
        <text>找到 {{ total }} 条结果</text>
      </view>

      <post-card
        v-for="post in postList"
        :key="post.id"
        :post="post"
        @click="goToDetail(post.id)"
      />

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-status">
        <u-loading mode="circle"></u-loading>
        <text class="ml-sm">加载中...</text>
      </view>

      <!-- 没有更多 -->
      <view v-if="!hasMore && postList.length > 0" class="no-more">
        没有更多了
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && postList.length === 0" class="empty-state">
        <u-empty mode="search" text="没有找到相关信息"></u-empty>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { postApi } from '@/api'
import type { Post } from '@/types'
import PostCard from '@/pages/index/components/PostCard.vue'
import { debounce } from '@/utils/common'

// 状态
const keyword = ref('')
const hasSearched = ref(false)
const postList = ref<Post[]>([])
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = 10
const total = ref(0)

// 搜索历史
const searchHistory = ref<string[]>([])
const hotKeywords = ref(['二手家具', '兼职招聘', '房屋出租', '同城配送', '废品回收'])

// 生命周期
onMounted(() => {
  // 加载搜索历史
  loadSearchHistory()
})

/**
 * 加载搜索历史
 */
const loadSearchHistory = () => {
  const history = uni.getStorageSync('searchHistory') || []
  searchHistory.value = history.slice(0, 10) // 最多显示10条
}

/**
 * 保存搜索历史
 */
const saveSearchHistory = (kw: string) => {
  if (!kw.trim()) return

  let history = uni.getStorageSync('searchHistory') || []

  // 移除重复项
  history = history.filter((item: string) => item !== kw)

  // 添加到开头
  history.unshift(kw)

  // 最多保存20条
  history = history.slice(0, 20)

  uni.setStorageSync('searchHistory', history)
  searchHistory.value = history.slice(0, 10)
}

/**
 * 清除搜索历史
 */
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确认清除搜索历史？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('searchHistory')
        searchHistory.value = []
      }
    }
  })
}

/**
 * 输入事件（防抖）
 */
const onInput = debounce(() => {
  // 可以在这里实现搜索建议功能
}, 300)

/**
 * 搜索
 */
const handleSearch = () => {
  if (!keyword.value.trim()) {
    uni.showToast({ title: '请输入搜索关键词', icon: 'none' })
    return
  }

  saveSearchHistory(keyword.value.trim())
  performSearch()
}

/**
 * 通过关键词搜索
 */
const searchByKeyword = (kw: string) => {
  keyword.value = kw
  handleSearch()
}

/**
 * 执行搜索
 */
const performSearch = async (isLoadMore = false) => {
  if (loading.value) return

  loading.value = true
  hasSearched.value = true

  try {
    const params: any = {
      keyword: keyword.value.trim(),
      page: isLoadMore ? page.value : 1,
      size: pageSize
    }

    const res = await postApi.search(params)

    if (isLoadMore) {
      postList.value.push(...res.list)
    } else {
      postList.value = res.list
      page.value = 1
    }

    total.value = res.pagination.total
    hasMore.value = res.pagination.hasMore
    page.value++
  } catch (err) {
    console.error('搜索失败:', err)
  } finally {
    loading.value = false
  }
}

/**
 * 加载更多
 */
const onLoadMore = () => {
  if (!hasMore.value || loading.value) return
  performSearch(true)
}

/**
 * 清除关键词
 */
const clearKeyword = () => {
  keyword.value = ''
  hasSearched.value = false
  postList.value = []
}

/**
 * 返回
 */
const goBack = () => {
  uni.navigateBack()
}

/**
 * 跳转到详情
 */
const goToDetail = (postId: number) => {
  uni.navigateTo({
    url: `/pages/detail/index?id=${postId}`
  })
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color-page);
}

.search-bar {
  display: flex;
  align-items: center;
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  gap: var(--spacing-sm);

  .search-input-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 16rpx 24rpx;
    background-color: var(--bg-color-page);
    border-radius: var(--radius-round);

    .search-input {
      flex: 1;
      margin: 0 var(--spacing-sm);
      font-size: 28rpx;
    }
  }

  .cancel-btn {
    font-size: 28rpx;
    color: var(--text-color);
  }
}

.suggestion-section {
  flex: 1;
  padding: var(--spacing-md);

  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: var(--spacing-md);

    .section-title {
      font-size: 32rpx;
      font-weight: 500;
      color: var(--text-color);
    }
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: var(--spacing-sm);

    .tag-item {
      padding: 16rpx 32rpx;
      background-color: var(--bg-color);
      border-radius: var(--radius-round);
      font-size: 28rpx;
      color: var(--text-color-secondary);

      &.hot {
        display: flex;
        align-items: center;
        gap: 8rpx;
        color: var(--text-color);
      }
    }
  }

  .history-section {
    margin-bottom: var(--spacing-xl);
  }
}

.result-section {
  flex: 1;
  padding: var(--spacing-md);

  .result-header {
    padding: var(--spacing-sm) 0;
    font-size: 24rpx;
    color: var(--text-color-secondary);
  }
}

.loading-status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-md);
  color: var(--text-color-secondary);
  font-size: 28rpx;
}

.no-more {
  text-align: center;
  padding: var(--spacing-md);
  color: var(--text-color-placeholder);
  font-size: 24rpx;
}

.empty-state {
  padding: 200rpx 0;
}
</style>
